﻿using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebDocDB.Managers;

namespace WebDocDB.DocumentDBManager
{
    public class DocumentCollectionsManager : IDocumentCollectionsManager
    {
        private DocumentClient _client;

        public DocumentCollectionsManager(IAccountManager accountManager)
        {
            var accountSettings = accountManager.GetAccountSettings();
            _client = new DocumentClient(new Uri(accountSettings.EndpointUrl), accountSettings.MasterKey,
                   new ConnectionPolicy { ConnectionMode = accountSettings.ConnectionMode, ConnectionProtocol = accountSettings.Protocol });
        }

        public async Task<List<WebDocDB.Models.DocumentCollection>> GetAllDatabaseCollections(string databaseLink)
        {
            FeedResponse<DocumentCollection> collections = await _client.ReadDocumentCollectionFeedAsync(databaseLink);

            var collList = new List<WebDocDB.Models.DocumentCollection>();

            foreach (var coll in collections)
            {
                collList.Add(new WebDocDB.Models.DocumentCollection() { ID = coll.Id, Link = coll.SelfLink });
            }            

            return collList;
        }

        public async Task AddDocumentCollection(string databaseLink, string collectionName)
        {
            try
            {

                var response = await _client.CreateDocumentCollectionAsync(databaseLink,
                    new DocumentCollection { Id = collectionName });

                //var collection = await RetrieveOrCreateCollectionAsync(databaseLink, collectionName);
                                
            }
            catch (AggregateException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public async Task DeleteDocumentCollection(string collectionLink)
        {
            try
            {

               var response = await _client.DeleteDocumentCollectionAsync(collectionLink);                

            }
            catch (AggregateException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}
